//
//  YZXEmojticonKeyboard.swift
//  表情键盘
//
//  Created by 叶周翔 on 16/7/28.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit

class YZXEmojticonKeyboard: UIView,emojticonViewDelegate  {
    // 在键盘中定义一个textView
    weak var textView:UITextView?
    private let layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {

        let newFrame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 216)
        super.init(frame: newFrame)
        setupUI()
        
    }
    
    private func setupUI() {
        self.addSubview(collectionView)
        self.addSubview(emojticonTool)
        self.addSubview(pageControl)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        emojticonTool.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        //约束
        self.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        
        self.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: emojticonTool, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
//        self.addConstraint(NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 191))
        
        // 按钮工具条
        self.addConstraint(NSLayoutConstraint(item: emojticonTool, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: emojticonTool, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: emojticonTool, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        self.addConstraint(NSLayoutConstraint(item: emojticonTool, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 44))
        
        // 添加约束
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 15))
    }
    // MARK:设置页码指示器
    private func setupPageControl(indexPath:NSIndexPath){
        pageControl.numberOfPages = YZXEmojiManager.shareManager.emojticonPackages[indexPath.section].allPageEmoji.count
        pageControl.currentPage = indexPath.item
        // 如果是只有一页的就不显示 
        pageControl.hidden = (YZXEmojiManager.shareManager.emojticonPackages[indexPath.section].allPageEmoji.count == 1)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layout.itemSize = self.collectionView.frame.size
        
      
    }
    
    
    
    //MARK:-懒加载
    private lazy var collectionView:UICollectionView = {
        let cv = UICollectionView(frame: CGRectZero,collectionViewLayout: self.layout)
        cv.delegate = self
        cv.dataSource = self
        //注册cell
        cv.registerClass(YZXKeyboardCell.classForCoder(), forCellWithReuseIdentifier: "cell")
        self.layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        cv.bounces = false
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        self.layout.minimumLineSpacing = 0
        self.layout.minimumInteritemSpacing = 0
        return cv
    }()
    
    private lazy var emojticonTool:YZXEmojticonView = {
        
       let emoji = YZXEmojticonView()
        
        emoji.delegate = self
        
        return emoji
    }()
    //页码指示器
    private lazy var pageControl:UIPageControl = {
        let pc = UIPageControl()
        pc.numberOfPages = 6
        pc.currentPage = 3
        // 在一开始的时候就隐藏控件 
        pc.hidden = true
        pc.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "currentPageImage")
        pc.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "pageImage")
        
        return pc
    }()
    
    
    
    private let sections: [Int] = [1,6,4,2]
}

// MARK:代理方法实现
extension YZXEmojticonKeyboard {
    func emojticonToolBar(didSelecedType type: EmoticonToolBarType) {
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        // 选中哪一个item
        collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
        
        // 设置pageContrl的页码
        self.setupPageControl(indexPath)
    }
}

extension YZXEmojticonKeyboard:UICollectionViewDataSource{
    // 返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return YZXEmojiManager.shareManager.emojticonPackages.count
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! YZXKeyboardCell
        
//        cell.backgroundColor = UIColor.randomColor()
        cell.backgroundColor = UIColor(red: 237.0/255.0, green: 237.0/255.0, blue: 237.0/255.0, alpha: 1)
        cell.indexPath = indexPath
        // 将cell对应这页的模型赋值
        let emotiocnPackage = YZXEmojiManager.shareManager.emojticonPackages[indexPath.section]
        
        // cell的表情包中的表情是每一组对应的所有表情
        cell.pageEmoticons = emotiocnPackage.allPageEmoji[indexPath.item]
        
        cell.delegate = self
        
        return cell
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return sections[section]
    }
}

extension YZXEmojticonKeyboard:UICollectionViewDelegate{
    // collectionView 在滚动的时候调用
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 获取中心点
        var centerPoint = collectionView.center
//        let offset = scrollView.contentOffset.x
        
        // 参考点要和frame是同一个起点
//        centerPoint.x += offset
        centerPoint.x += scrollView.contentOffset.x
        
        for cell in collectionView.visibleCells(){
            if cell.frame.contains(centerPoint){
                // 获取当前的indexPath
                let indexPath = collectionView.indexPathForCell(cell)
                // 将这个indexPath对应的组传进去
                emojticonTool.choseButtonWithIndexPath(indexPath!.section)
                self.setupPageControl(indexPath!)
            }
        }
    }
}

extension YZXEmojticonKeyboard:YZXKeyboardCellDelegate{
    // 实现代理方法
    func emojiBtnClick(emojiModel model: YZXEmoticonModel) {
                
        textView?.inserEmoticon(model)
        YZXEmojiManager.shareManager.addRecentEmoji(model)
    }
    
    // 删除按钮的代理方法
    func deleteBtnDidClick() {
        textView?.deleteBackward()
    }
    
    
}